package com.example.seckill.application.impl;

import com.example.seckill.application.service.StockService;
import com.example.seckill.applicatoin.exception.ResultCodeMapper;
import com.example.seckill.applicatoin.exception.SystemException;
import com.example.seckill.domain.model.Product;
import com.example.seckill.domain.repository.ProductRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author Martin
 */
@Service
@Slf4j
public class StockServiceImpl implements StockService {
    @Autowired
    private ProductRepository productRepository;

    /**
     * 获取商品库存
     * @param product 商品ID
     * @return 商品库存
     */
    @Override
    public int getStock(Product product ) {

        log.info("获取礼品{}，可用库存为：{}",product.getName(),product.getStockAvailable());
        return product.getStockAvailable();
    }

    /**
     * 减少商品库存
     * @param product 商品ID
     * @param quantity 减少数量
     * @return 是否减少成功
     */
    @Override
    public void reduceStock(Product product, int quantity) {
        product.reduceStock(quantity);
    }
    /**
     * 减库存
     * @param product 商品ID
     * @param quantity 减少的数量
     * @return 是否减库存成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reduceStockV2(Product product, int quantity) {

        int remaining = product.getStockAvailable() - quantity;
        log.info("==========product.getStockAvailable(): {}",product.getStockAvailable());
        if (remaining < 0) {
            throw new SystemException("库存不足",ResultCodeMapper.STOCK_ERROR);
        }
        product.setStockAvailable(remaining);
        productRepository.save(product);

    }

    /**
     * 增加商品库存
     * @param productId 商品ID
     * @param quantity 增加数量
     * @return 是否增加成功
     */
    @Override
    public boolean increaseStock(Long productId, int quantity) {
        Optional<Product> productOptional = productRepository.findById(productId);
        if (!productOptional.isPresent()) {
            return false;
        }
        Product product = productOptional.get();
        int stock = product.getStockAvailable();
        product.setStockAvailable(stock + quantity);
        productRepository.save(product);
        return true;
    }
}

